/**
 * Created by ZhangJiating on 17-4-19.
 */
(function($){
    var ipBox = (function(){
        function ipBoxFun(element,options){
            this.params = $.extend(true,$.fn.ipBox.defaults,options||{});
            this.element = element;
            this.init();
        };
        ipBoxFun.prototype = {
            //初始化ipBox插件相关方法
            init : function(){
                var self=this;
                self.createIpInput();
                self.setDefaultIp();
                self.inputEvent();
            },
            createIpInput : function(){
                var self=this;
                var settings=self.params;
                self.outTitle=$('<label class="ip-out-title">'+settings.titleText+'</label>');
                self.ipWrap=$('<div class="ip-wrap title-in port-in">'+
                    '<div class="inner-box">'+
                    '<label class="ip-in-title">'+settings.titleText+'</label>'+
                    '<input type="text" class="ip-value" maxlength="3"/><span>.</span>'+
                    '<input type="text" class="ip-value" maxlength="3"/><span>.</span>'+
                    '<input type="text" class="ip-value" maxlength="3"/><span>.</span>'+
                    '<input type="text" class="ip-value node" maxlength="3"/>'+
                    '</div>'+
                    '<span class="separates">/</span>'+
                    '<input type="text" class="ip-port ip-value" maxlength="2"/>'+
                    '</div>');
                self.point=$('<span class="ip-point">'+settings.defaultPoint+'</span>');
                self.outTitle.add(self.ipWrap).add(self.point).appendTo(self.element);
                self.initIpWrap();
            },
            initIpWrap : function(){
                var self=this,
                    settings=self.params,
                    element = self.element;
                element.addClass("ip-box");
                if(settings.port){
                    element.find(".node").attr("maxlength","1");
                }else{
                    self.ipWrap.removeClass("port-in");
                    element.find(".separates").remove();
                    element.find(".ip-port").remove();
                    element.find("input:last").removeClass("node").attr("maxlength","3");
                }
                if(settings.titleOut){
                    element.find(".ip-in-title").remove();
                    element.find(".ip-wrap").removeClass("title-in");
                }else{
                    element.find(".ip-out-title").remove();
                }
                if(settings.noPoint){
                    self.point.remove();
                }
                if(settings.portIn){
                    self.ipWrap.addClass("inner-port");
                }
                element.attr("data-ip","");
            },
            inputFocus : function(){
                var self=this;
                self.element.addClass("on");
            },
            inputBlur : function(){
                var self=this;
                self.element.removeClass("on");
            },
            ipImport : function(e){
                if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=9 && !(e.keyCode>=37&&e.keyCode<=40)&& !(e.keyCode>=48 && e.keyCode<=57) && !(e.keyCode>=96 && e.keyCode<=105)){
                    e.preventDefault();
                }
            },
            inputValChange : function(){
                var that=$(this),
                    valLen=$(that).val().length;
                if(valLen==3){
                    $(that).next().next().focus();
                    if($(that).val()>255){
                        $(that).val("255");
                    }
                }
                if($(that).hasClass("node")){
                    if($(that).val()>0){
                        $(that).val("0");
                    }
                    $(that).closest(".ip-wrap").find(".ip-port").focus();
                }
                if($(that).hasClass("ip-port")){
                    if(($(that).val().length==2)&&($(that).val()<16 || $(that).val()>29)){
                        $(that).val("");
                    }
                }
            },
            getIpValue : function(settings){
                var self=$(this);
                var ip="";
                $(this).find("input").each(function(){
                    ip+=$(this).val()+".";
                })
                if(settings.port){
                    ip=ip.substr(0,ip.length-1);
                    ip = ip.substring(ip.lastIndexOf("."), 0) + "/" + ip.substring(ip.lastIndexOf(".")+1,ip.length);
                }else{
                    ip=ip.substr(0,ip.length-1)
                }
                if(ip=="..."||ip==".../"){
                    ip="";
                }
                self.attr("data-ip",ip);
            },
            validate:function(ip){//验证输入内容格式
                var self=this,
                    settings=self.params;
                if(ip==""){
                    return true
                }
                if(!settings.filter){
                    return true
                }
                return settings.filter.test(ip);
            },
            errorPrompt : function(ip){
                var self=this,
                    settings=self.params;
                if(!self.validate(ip)){
                    self.element.addClass("error");
                    self.point.addClass("error").text(settings.errorPoint);
                }else{
                    self.element.removeClass("error");
                    self.point.removeClass("error").text(settings.defaultPoint);
                }
            },
            blurCheck : function(e){
                var self=this;
                var ip=self.element.attr("data-ip");
                $(document).on("click.checkIp",function(e){
                    var evt=e.target;
                    if($(evt).closest("on").length==0){
                        self.errorPrompt(ip);
                    }
                    $(document).off("click.checkIp");
                })
            },
            ipValue: function(arr){
                var self=this,
                    element=self.element;
                if(!!arr){
                    element.find("input").each(function(i){
                        $(this).val(arr[i]);
                    });
                }
            },
            setDefaultIp: function(){
                var self=this,
                    settings=self.params,
                    defaultVal=settings.ipValue;
                if(!!defaultVal){
                    var arr=defaultVal.split(".");
                    var arr1=[];
                    if(settings.port){
                        arr1=arr1.concat(arr.slice(0,arr.length-1),arr[arr.length-1].split("/"));
                    }else{
                        arr1=arr;
                    }
                };
                self.element.attr("data-ip",defaultVal);
                self.ipValue(arr1);
            },
            inputEvent : function(){
                var self=this,
                    settings=self.params;
                var ipInput=self.element.find("input");
                ipInput.on("focus",function(){self.inputFocus();})
                    .on("blur",function(){self.inputBlur();})
                    .on("keydown",function(e){self.ipImport(e)})
                    .on("input propertychange",function(e){
                        self.inputValChange.call($(this));
                        self.getIpValue.call($(this).closest(".ip-box"),settings);
                        self.blurCheck(e);
                    })
            }
        }
        return ipBoxFun;
    })();
    $.fn.ipBox = function(options){
        return this.each(function(){
            var me = $(this),
                instance = me.data("myIp");
            if(!instance){
                instance = new ipBox(me,options);
                me.data("myIp",instance);
            }
            if($.type(options) === "string"){
                return instance[options]();
            }
        });
    };

    //设置插件相关配置参数
    $.fn.ipBox.defaults = {
        port : false,                                      //IP地址有无端口号
        portIn : false,                                    //控制端口号输入框位置
        titleText : "ip段",                                //title文字
        titleOut : true,                                  //title相对于输入框的位置
        filter : null,                                    //校验IP正则
        ipValue : "",                                      //是否存在初始值
        noPoint : false,                                  //是否有提示信息默认有
        defaultPoint : "(例192.168.100.0/24)",             //提示信息
        errorPoint : "输入格式错误(例192.168.100.0/24)"    //错误提示
    }
})(jQuery);